package charlie.shop.warehouse;

import charlie.shop.misc.Common;
import com.charlie.beans.Product;
import com.charlie.db.DAOLocal;
import com.charlie.sessions.ProductFacadeLocal;
import java.io.IOException;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ListOfProducts servlet displays catalog with guitars.
 * We are able to add/delete guitars.
 * 
 * @author Gleb
 */
@WebServlet(name = "ListOfProducts", urlPatterns = {"/warehouse/products"})
public class ListOfProducts extends HttpServlet {

    /**
     * Items per page limit static constant
     */
    private static final int ITEMS_PER_PAGE = 20;
    @EJB
    private ProductFacadeLocal productFacade;
    @EJB
    private DAOLocal dao;

    /**
     * Calculate number of pages, current page, put range of products into request
     * 
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int page = Common.getPage(request);
        int itemsCount = productFacade.count();
        int pagesCount = (int) Math.ceil((float) itemsCount / (float) ITEMS_PER_PAGE);

        List<Product> products = null;

        if (page <= pagesCount) {
            products = dao.getProductRange(((page - 1) * ITEMS_PER_PAGE), (page * ITEMS_PER_PAGE));
        }

        request.setAttribute("productList", products);
        request.setAttribute("page", page);
        request.setAttribute("pagesCount", pagesCount);

        getServletContext().getRequestDispatcher("/warehouse/ListOfProducts.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}
